import { createStore } from "vuex";

export default createStore({
  state: {
    isCollapse: true,
    currentMenu: null,
    tabList: [
      {
        path: "/",
        name: "home",
        label: "首页",
        icon: "home",
      },
    ],
    menu: [],
    token: "",
    username: "",
    userPermission: "",
  },
  mutations: {
    updateIsCollapse(state) {
      state.isCollapse = !state.isCollapse;
    },
    selectMenu(state, val) {
      if (val.name == "home") {
        state.currentMenu = null;
      } else {
        state.currentMenu = val;
        const result = state.tabList.findIndex(
          (item) => item.name === val.name
        );
        if (result === -1) {
          state.tabList.push(val);
        }
      }
    },
    closeTab(state, val) {
      const res = state.tabList.findIndex((item) => item.name === val.name);
      state.tabList.splice(res, 1);
    },
    setToken(state, val) {
      state.token = val;
      sessionStorage.setItem("token", val);
    },
    clearToken(state) {
      state.token = "";
      sessionStorage.removeItem("token");
    },
    getToken(state) {
      state.token = sessionStorage.getItem("token") || state.token;
    },
    setUserLabel(state, val) {
      state.username = val;
      sessionStorage.setItem("username", val);
      state.userPermission = val === "admin" ? "超级管理员" : "普通用户";
    },
    getUserLabel(state) {
      state.username = sessionStorage.getItem("username") || state.username;
      state.userPermission =
        state.username === "admin" ? "超级管理员" : "普通用户";
    },
    setMenu(state, val) {
      state.menu = val;
      sessionStorage.setItem("menu", JSON.stringify(val));
    },
    clearMenu(state) {
      state.menu = [];
      sessionStorage.removeItem("menu");
    },
    addMenu(state, router) {
      if (!sessionStorage.getItem("menu")) {
        return;
      }
      const menu = JSON.parse(sessionStorage.getItem("menu"));
      state.menu = menu;
      const menuArray = JSON.parse(sessionStorage.getItem("addRoute")) || [];
      const modules = import.meta.glob("../views/**/*.vue");

      menu.forEach((item) => {
        if (item.children) {
          item.children = item.children.map((item) => {
            item.component = modules[`../views/${item.url}`];
            return item;
          });
          menuArray.push(...item.children);
        } else {
          item.component = modules[`../views/${item.url}`];
          menuArray.push(item);
        }
      });
      //路由动态添加
      menuArray.forEach((item) => {
        router.addRoute("Main", item);
      });
      sessionStorage.setItem("addRoute", JSON.stringify(menuArray));
    },
  },
});
